import { showLoading, showError, closeLoading } from "@/utils/vant";
import { queryNewsList } from "@/api/chkNum";
import { chunkArray } from "@/utils";

interface Params {
  id?: string | number;
  tag?: string;
  page?: number;
  size?: number;
}
const useLotNews = defineStore("lotNews", () => {
  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const newsList = ref<any>([]);
  const chunkedNewsList = ref<any>([]);
  const total = ref(0);
  const params = reactive<Params>({
    id: "",
    tag: "",
    page: 1,
    size: 20
  });
  function reset() {
    params.page = 1;
    params.size = 20;
    total.value = 0;
    newsList.value = [];
    chunkedNewsList.value = [];
    finished.value = false;
    refreshing.value = false;
    loading.value = true;
  }
  async function fetchData() {
    try {
      showLoading();
      const res = await queryNewsList(params);
      chunkedNewsList.value = [];
      const pList = res.data.list;
      newsList.value = newsList.value.concat(pList);
      chunkedNewsList.value = chunkArray(newsList.value, 4);
      if (params.page === 1) {
        total.value = res.data.total;
      }
      if (unref(newsList).length >= total.value) {
        finished.value = true;
      }
    } catch (error) {
      showError(error);
    } finally {
      loading.value = false;
      closeLoading();
      nextTick(() => {
        exec.value = false;
      });
    }
  }
  const exec = ref(false);
  const onLoad = () => {
    exec.value = true;
    if (unref(newsList).length) {
      params.page = (params.page || 1) + 1;
    }
    fetchData();
  };

  const onRefresh = () => {
    reset();
    onLoad();
  };

  return {
    // newsList,
    exec,
    fetchData,
    chunkedNewsList,
    loading,
    finished,
    refreshing,
    onLoad,
    onRefresh
  };
});
export const useLotNewsRefs = () => storeToRefs(useLotNews());
export default useLotNews;
